package com.qth.valet.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qth.valet.common.theadlocal.UserOrDriverIdHolder;
import com.qth.valet.common.utils.ResponseResult;
import com.qth.valet.common.utils.StatusConstants;
import com.qth.valet.entity.po.NoticeDriver;
import com.qth.valet.service.DriversService;
import com.qth.valet.service.NoticeDriverService;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
@RequestMapping("/qth/notice_driver")
public class NoticeDriverController {

    private final NoticeDriverService noticeDriverService;

    private final DriversService driversService;

    /**
     * 司机查询通知分页
     */
    @GetMapping("/page")
    @Transactional(rollbackFor = Exception.class) // 加不加事务都无所谓
    public ResponseResult<Page<NoticeDriver>> page(@RequestParam int pageNum, @RequestParam int pageSize) {
        // 查询分页
        Page<NoticeDriver> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<NoticeDriver> qw = new LambdaQueryWrapper<NoticeDriver>()
                .eq(NoticeDriver::getDriverId, UserOrDriverIdHolder.getDriverId())
                .or()
                .eq(NoticeDriver::getType, StatusConstants.NOTICE_SYSTEM)
                .orderByDesc(NoticeDriver::getId);
        Page<NoticeDriver> res = noticeDriverService.page(page, qw);
        // 将司机的通知读取状态改为已读
        driversService.updateNoticeReadStatus(UserOrDriverIdHolder.getDriverId(), true);
        // 返回结果
        return ResponseResult.success(res);
    }

    /**
     * 查询司机是否有未读消息
     */
    @GetMapping("/hasReadNotices")
    public ResponseResult<Boolean> hasReadNotices() {
        return ResponseResult.success(driversService.getById(UserOrDriverIdHolder.getDriverId()).getIsNoticeRead());
    }

}
